package com.xpec.c4.db.log;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xpec.c4.db.basic.BasicLogDAO;
import com.xpec.c4.db.model.log.basic.BasicLogModel;

/**
 * 负责把日志对象存到DB的线程类
 * 
 * @author zhongzhengkai 2011-11-25
 */
public class SaveLogTask implements Runnable {

	private Log log = LogFactory.getLog(SaveLogTask.class);

	/**
	 * 定时存储时一次批量可存储的日志个数
	 */
	private static int saveNum = LogPoolConstants.SAVE_NUM;

	@Override
	public void run() {
		int len = LogModelPool.getPoolSize();
		if (len != 0) {
			if(log.isInfoEnabled()){
				log.info(" saving logs begin!");
			}
			List<BasicLogModel> saveLogs = new ArrayList<BasicLogModel>();
			List<BasicLogModel> partOfSaveLogs = new ArrayList<BasicLogModel>();

			for (int i = 0; i < len; i++) {
				saveLogs.add(LogModelPool.poll());
			}
//			for (BasicLogModel basicLogModel : saveLogs) {
//				HibernateManager.txBegin();
//				BasicLogDAO.saveLog(basicLogModel);
//			}

			int i = 0;
			for (BasicLogModel ilog : saveLogs) {
				if (ilog != null) {
					partOfSaveLogs.add(ilog);
				}
				i++;

				if (i % saveNum == 0 || i == saveLogs.size()) {
					if (!BasicLogDAO.saveLogs(partOfSaveLogs)) {
						for (BasicLogModel slog : partOfSaveLogs) {
							try {
								if (!BasicLogDAO.saveLog(slog)) {
									log.error("save log " + slog.getClass()
											+ " " + slog + " failed!");
								}
							} catch (Exception e) {
								log.error("save log " + slog.getClass() + " "
										+ slog + " failed!");
							}
						}
						partOfSaveLogs.clear();
					} else {
						
						if (log.isInfoEnabled()) {
							log.info("Logs Caculation:" + saveLogs.size()
									+ " Log had been saved successfully!");
						}
						partOfSaveLogs.clear();
					}
				}
			}

			if(log.isInfoEnabled()){
				log.info(" save complete!");
			}
		}
	}

}
